package com.joint.web.action.manage;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.Company;
import com.joint.base.entity.Users;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.DepartmentService;
import com.joint.base.service.activiti.WorkflowService;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.manage.AssetUse;
import com.joint.core.entity.manage.Purchase;
import com.joint.core.service.AssetUseService;
import com.joint.core.service.PurchaseService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ZhuChunXiao on 2017/3/28.
 */
@ParentPackage("manage")
public class AjaxAssetuseAction extends BaseFlowAction {
    @Resource
    private WorkflowService workflowService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private AssetUseService assetUseService;
    @Resource
    private PurchaseService purchaseService;

    /**
     * 固定资产名称
     */
    private String name;
    /**
     * 固定资产型号
     */
    private String type;
    /**
     * 固定资产编号
     */
    private String no;
    /**
     * 资产登记表Id
     */
    private String purchaseId;
    /**
     * 采购金额
     */
    private String money;
    /**
     * 采购日期
     */
    private String date;
    /**
     * 使用部门
     */
    private String departmentId;
    /**
     * 使用人
     */
    private String userId;

    private AssetUse assetUse;
    private Purchase purchase;
    private int numStatus;
    private Users loginUser;
    private List<Map<String,Object>> purchaseList;
    private List<AssetUse> assetUseList;

    public String execute(){
        return "assetuse";
    }

    public String list(){
        pager = new Pager(0);
        /*
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);*/
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);
        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();
        Map<String,Object> params = new HashMap<String,Object>();
       // params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        //所有单子
        params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
        pager=assetUseService.findByPagerAndLimit(true, "assetuse", pager, params);
        List<AssetUse> assetUseList;
        if (pager.getTotalCount() > 0){
            assetUseList = (List<AssetUse>) pager.getList();
        }else{
            assetUseList= new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(AssetUse assetUse: assetUseList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",assetUse.getId());
            rMap.put("year",DataUtil.DateToString(assetUse.getCreateDate(), "yyyy"));
            rMap.put("month",DataUtil.DateToString(assetUse.getCreateDate(), "MM"));
            rMap.put("no",assetUse.getNo());
            rMap.put("creater", assetUse.getCreater() != null ? assetUse.getCreater().getName() : "");
            rMap.put("department",assetUse.getDepartment().getName());
            rMap.put("createDate", DataUtil.DateToString(assetUse.getCreateDate(),"yyyy-MM-dd"));
            rMap.put("state",assetUse.getProcessState().value());
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }

        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records", recordsNum);
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String read(){
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)){
            assetUse=assetUseService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);
        }
        return "read";
    }

    public String input(){
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
        params.put("step", "3");
        Company company = usersService.getCompanyByUser();
        List<Purchase> list = (List<Purchase>)purchaseService.findByPagerAndCompany(null, null, company, params).getList();
        purchaseList= Lists.newArrayList();
        Map<String,Object> rmap;
        if (StringUtils.isNotEmpty(keyId)){
            assetUse = assetUseService.get(keyId);
            for(Purchase p:list){
                rmap= Maps.newHashMap();
                rmap.put("id",p.getId());
                rmap.put("name", "收款方："+p.getToName());
                if(assetUse.getPurchase()!=null && StringUtils.equals(p.getId(), assetUse.getPurchase().getId())) {
                    rmap.put("selected","selected");
                }
                purchaseList.add(rmap);
            }
        }else{
            if(list.size()>0){
                for(Purchase p:list){
                    rmap= Maps.newHashMap();
                    rmap.put("id", p.getId());
                    rmap.put("name", "收款方："+p.getToName());
                    rmap.put("selected","");
                    purchaseList.add(rmap);
                }
            }
        }
        return "input";
    }

    public void setData(){
        if(StringUtils.isNotEmpty(keyId)){
            assetUse=assetUseService.get(keyId);
        }else{
            assetUse=new AssetUse();
            assetUse.setCreater(usersService.getLoginInfo());
        }
        assetUse.setPurchase(purchaseService.get(purchaseId));
        assetUse.setName(name);
        assetUse.setType(type);
        assetUse.setNo(no);
        assetUse.setMoney(money);
        assetUse.setDate(DataUtil.StringToDate(date));
        assetUse.setDepartment(departmentService.get(departmentId));
        assetUse.setUser(usersService.get(userId));
        assetUse.setCompany(usersService.getLoginInfo().getCompany());
    }

    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                assetUseService.update(assetUse);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                assetUseService.save(assetUse, "assetuse", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    public String commit(){
        setData();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                assetUseService.approve(assetUse, FlowEnum.ProcessState.Finished, var2, curDutyId, comment);
            } else {
                keyId =  assetUseService.commit(assetUse, FlowEnum.ProcessState.Finished, "assetuse", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }



    public void exportExcel()  {
        pager = new Pager(0);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("state", new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        Company company = usersService.getCompanyByUser();
        pager = assetUseService.findByPagerAndCompany(pager,null,company,params);
        assetUseList = (List<AssetUse>) pager.getList();
        List<AssetUse> list1 = new ArrayList();
        OutputStream outputStream = null;
        // String now  = DataUtil.DateToString(new Date(),"yyyyMMddHHmmss");
        // String rand = CommonUtil.getRandomString(6);
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet("Sheet1");
        for(int i=0; i<=7;i++){
            sheet.setColumnWidth(i, 20 * 256);
        }
        CellStyle style = workbook.createCellStyle();
        HSSFFont font = workbook.createFont();
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示
        style.setFont(font);
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("采购登记表");
        row.createCell(1).setCellValue("固定资产名称");
        row.createCell(2).setCellValue("固定资产型号");
        row.createCell(3).setCellValue("固定资产编号");
        row.createCell(4).setCellValue("采购金额");
        row.createCell(5).setCellValue("采购日期");
        row.createCell(6).setCellValue("使用部门");
        row.createCell(7).setCellValue("使用人");
        for(int i=0; i<=7;i++){
            row.getCell(i).setCellStyle(style);
        }
        String fileName = "资产使用登记表.xls";
        for(AssetUse assetUse:assetUseList){
            list1.add(assetUse);
        }
        for(int i=0; i<list1.size(); i++){
            AssetUse assetUse = list1.get(i);
            row = sheet.createRow(i+1);
            row.createCell(0).setCellValue("收款方："+assetUse.getPurchase().getToName());
            row.createCell(1).setCellValue(assetUse.getName());
            row.createCell(2).setCellValue(assetUse.getType());
            row.createCell(3).setCellValue(assetUse.getNo());
            row.createCell(4).setCellValue(assetUse.getMoney());
            row.createCell(5).setCellValue(DataUtil.DateToString(assetUse.getDate()));
            row.createCell(6).setCellValue(assetUse.getDepartment().getName());
            row.createCell(7).setCellValue(assetUse.getUser().getName());
        }
        try {
            outputStream = new FileOutputStream("/temp/"+fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        OutputStream out = null;
        HttpServletRequest request = ServletActionContext.getRequest();
        //  if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {

        //  }
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/plain;charset=utf-8");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        try {
            response.setHeader("content-disposition", "attachment;filename="+new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            out = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        InputStream in = null;
        try {
            in = new FileInputStream("/temp/"+fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        byte[] buffer = new byte[1024];
        int i = -1;
        try {
            while ((i = in.read(buffer)) != -1) {
                out.write(buffer, 0, i);
            }
            out.flush();
            out.close();
            in.close();
            out = null;
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getNo() {
        return no;
    }

    public void setNo(String no) {
        this.no = no;
    }

    public String getPurchaseId() {
        return purchaseId;
    }

    public void setPurchaseId(String purchaseId) {
        this.purchaseId = purchaseId;
    }

    public String getMoney() {
        return money;
    }

    public void setMoney(String money) {
        this.money = money;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getDepartmentId() {
        return departmentId;
    }

    public void setDepartmentId(String departmentId) {
        this.departmentId = departmentId;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public AssetUse getAssetUse() {
        return assetUse;
    }

    public void setAssetUse(AssetUse assetUse) {
        this.assetUse = assetUse;
    }

    public Purchase getPurchase() {
        return purchase;
    }

    public void setPurchase(Purchase purchase) {
        this.purchase = purchase;
    }

    @Override
    public int getNumStatus() {
        return numStatus;
    }

    @Override
    public void setNumStatus(int numStatus) {
        this.numStatus = numStatus;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public List<Map<String, Object>> getPurchaseList() {
        return purchaseList;
    }

    public void setPurchaseList(List<Map<String, Object>> purchaseList) {
        this.purchaseList = purchaseList;
    }

    public List<AssetUse> getAssetUseList() {
        return assetUseList;
    }

    public void setAssetUseList(List<AssetUse> assetUseList) {
        this.assetUseList = assetUseList;
    }
}
